package net.gazhi.delonix.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 字符串加密算法
 * 
 * @author Jeffrey Lin
 *
 */
public class StringEncrypt {

	/**
	 * 先 sha256，加盐，再 sha256
	 * 
	 * @param str
	 * @param salt
	 * @return
	 */
	public static String dsha256(String str, String salt) {
		return StringEncrypt.sha256(StringEncrypt.sha256(str), salt);
	}

	/**
	 * 加盐再 sha256
	 * 
	 * @param str
	 * @param salt
	 * @return
	 */
	public static String sha256(String str, String salt) {
		return StringEncrypt.sha256(str + salt);
	}

	/**
	 * 对字符串做 SHA-256 运算，并转成全大写格式
	 * 
	 * @param str
	 * @return
	 */
	public static String sha256(String str) {
		String encName = "SHA-256";
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = str.getBytes();
		try {
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
		return strDes.toUpperCase();
	}

	/**
	 * 把byte数组的值转成字符串
	 * 
	 * @param bts
	 * @return
	 */
	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}

	public static void main(String[] args) {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		String str = null;
		String salt = null;
		try {
			System.out.print("请输入要计算 sha256 的字符串：");
			str = br.readLine();
			System.out.print("请输入盐值：");
			salt = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("sha256(\"" + str + "\") = " + sha256(str).toUpperCase());
		System.out.println("dsha256(\"" + str + "\", \"" + salt + "\") = " + dsha256(str, salt));
	}
}
